package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.enums.*;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author hanzishuai
 * @date 2025/4/9 22:23
 * @Description 帖子接口
 */
@Tag(name = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;


    @Operation(summary = "发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @Parameter(description = "板块Id") @RequestParam("boardId") @NonNull Long boardId,
                            @Parameter(description = "帖子标题") @RequestParam("title") @NonNull String title,
                            @Parameter(description = "帖子内容") @RequestParam("content") @NonNull String content) {

        // 校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == UserStatus.IS_BANNED.getCode()) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 板块校验
        Board board = boardService.selectById(boardId);
        if (board == null
                || board.getDeleteState() == BoardStatus.IS_DELETE.getStatus()
                || board.getState() == BoardStatus.IS_BANNED.getStatus()) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        // 封装帖子对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());

        // 调用 Service
        articleService.create(article);

        return AppResult.success();
    }


    @Operation(summary = "获取帖子列表")
    @GetMapping("/getListByBoardId")
    public AppResult<List<Article>> getListByBoardId(@Parameter(description = "板块Id")
                                                     @RequestParam(value = "boardId", required = false) Long boardId) {

        List<Article> articles;
        if (boardId == null) {
            articles = articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }

        if (articles == null) {
            // 如果 articles 为空，那么在经过 JSON 序列化后，前端接收到的就是一个字符串 “NULL”，这不是我想要的
            articles = new ArrayList<>();
        }

        return AppResult.success(articles);
    }


    @Operation(summary = "根据帖子 Id 获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @Parameter(description = "帖子 Id") @RequestParam("id") @NonNull Long id) {

        // 从 session 中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);


        // 根据帖子 Id 获取详情
        Article article = articleService.selectDetailById(id);

        if (article == null || article.getDeleteState() == ArticleStatus.IS_DELETE.getStatus()) {
            log.warn("{}", ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (article.getState() == ArticleStatus.IS_BANNED.getStatus()) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 判断当前用户是否为作者
        if (Objects.equals(user.getId(), article.getUserId())) {
            // 标识为作者
            article.setOwn(true);
        }

        return AppResult.success(article);
    }


    @Operation(summary = "修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @Parameter(description = "帖子Id") @RequestParam("id") @NonNull Long id,
                            @Parameter(description = "帖子标题") @RequestParam("title") @NonNull String title,
                            @Parameter(description = "帖子内容") @RequestParam("content") @NonNull String content) {
        HttpSession session = request.getSession(false);


        // 从 session 中获取 User 对象
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 校验
        if (user.getState() == UserStatus.IS_BANNED.getCode()) {
            log.warn("用户被禁言，无法修改帖子。userId = {}", user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 查询帖子
        Article article = articleService.selectById(id);
        // 校验
        if (article == null || article.getDeleteState() == ArticleStatus.IS_DELETE.getStatus()) {
            log.warn("{}", ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 判断用户是不是作者或管理
        if (!user.getId().equals(article.getUserId()) && user.getIsAdmin() != AdminStatus.IS_ADMIN.getStatus()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        articleService.modify(id, title, content);

        log.info("更新帖子成功，Article id = {}，User id = {}", article.getId(), user.getId());

        return AppResult.success();
    }

    @PostMapping("/thumbsUp")
    @Operation(summary = "点赞接口")
    public AppResult thumbsUp(HttpServletRequest request,
                              @Parameter(description = "帖子 Id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否被禁言
        if (user.getState() == UserStatus.IS_BANNED.getCode()) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //  校验帖子状态
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == ArticleStatus.IS_DELETE.getStatus()) {
            log.warn("{}", ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (article.getState() == ArticleStatus.IS_BANNED.getStatus()) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 调用 Service
        articleService.thumbsUpById(id);

        return AppResult.success();
    }

    @Operation(summary = "删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @Parameter(description = "帖子 Id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否被禁言
        if (user.getState() == UserStatus.IS_BANNED.getCode()) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //  校验帖子状态
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == ArticleStatus.IS_DELETE.getStatus()) {
            log.warn("{}", ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 判断用户是不是作者、管理
        if (!user.getId().equals(article.getUserId()) && user.getIsAdmin() != AdminStatus.IS_ADMIN.getStatus()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        // 调用 Service
        articleService.deleteById(article.getId());

        return AppResult.success();
    }

    @Operation(summary = "根据用户 Id 获取帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @Parameter(description = "用户 Id") @RequestParam(value = "userId", required = false) Long userId) {

        // 如果 userId 为空，从 Session 中获取当前登录用户的 Id
        if (userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);

            userId = user.getId();
        }

        // 调用 Service
        List<Article> articles = articleService.selectByUserId(userId);


        return AppResult.success(articles);
    }



    @Operation(summary = "搜索帖子功能")
    @GetMapping("/search")
    public AppResult<List<Article>> search(@Parameter(description = "要查找的帖子标题") @RequestParam("keyword") @NonNull String keyword) {
        // 校验 keyword
        if (keyword == null) {
            log.warn("输入的内容为空");
            return AppResult.failed("输入的内容为空");
        }

        // 根据 keyword 模糊查询帖子
        List<Article> articles = articleService.search(keyword);

        if (articles == null) {
            // 如果 articles 为空，那么在经过 JSON 序列化后，前端接收到的就是一个字符串 “NULL”，这不是我想要的
            articles = new ArrayList<>();
        }

        return AppResult.success(articles);

    }

}













